package com.junke.question.service.utils;

import com.junke.question.service.entity.SysUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class JwtUtil {
    /**
     * id
     */
    private String id;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 秘钥
     */
    private final static byte[] SECRET  = "6MNSobBRCHGIO0fS6MNSobBRCHGIO0fS".getBytes();

    /**
     * 有效期
     */
    private long expiration = 3600000000L;

    /**
     * 权限
     */
    private String role;


    /**
     * 创建Token
     * @param userName
     * @return
     */
    public String createToken(String userName){
        return Jwts.builder()
                .setHeaderParam("type","JWT")
                .setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     *  获取用户权限
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(String userId){
        // 角色(ROLE_admin), 菜单操作权限 save
        // ROLE_admin,save,update
        String authority = "admi";
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }


    /**
     * description: 从token中获取用户名
     *
     * @param token
     * @return java.lang.String
     */
    public String getUsername(String token){
        return getClaimsFromToken(token).getSubject();
    }

    /**
     * 获取用户角色
     * @param token
     * @return
     */
    public List<String> getUserRole(String token){
        return (List<String>) getClaimsFromToken(token).get(role);
    }

    /**
     * description: 判断Token是否过期
     *
     * @param token
     * @return boolean
     */
    public boolean isExpiration(String token){
        return getClaimsFromToken(token).getExpiration().before(new Date());
    }

    /**
     * description:　获取Claims
     *
     * @param token
     * @return io.jsonwebtoken.Claims
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }
}
